package com.leyou.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.pojo.PageResult;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.TbBrand;
import com.leyou.item.entity.TbCategoryBrand;
import com.leyou.item.mapper.TbBrandMapper;
import com.leyou.item.service.TbBrandService;
import com.leyou.item.service.TbCategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 品牌表，一个品牌下有多个商品（spu），一对多关系 服务实现类
 * </p>
 *
 * @author mybaitsplus
 * @since 2019-10-18
 */
@Service
public class TbBrandServiceImpl extends ServiceImpl<TbBrandMapper, TbBrand> implements TbBrandService {
    @Autowired
    private TbCategoryBrandService categoryBrandService;

    @Override
    public PageResult<BrandDTO> searchPage(Integer page, Integer rows, String key, String sortBy, Boolean desc) {
        Page p = new Page<TbBrand>(page, rows);
        QueryWrapper<TbBrand> queryWrapper = new QueryWrapper<>();
        //条件判断，添加
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.lambda().like(TbBrand::getName, key).or().like(TbBrand::getLetter, key);
        }
        if (!StringUtils.isEmpty(sortBy)) {
            if (desc) {
                p.setDesc(sortBy);
            } else {
                p.setAsc(sortBy);
            }
        }
        IPage iPage = this.page(p, queryWrapper);
        if (iPage == null || CollectionUtils.isEmpty(iPage.getRecords())) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        List<BrandDTO> brandDTOS = BeanHelper.copyWithCollection(iPage.getRecords(), BrandDTO.class);
        return new PageResult(iPage.getTotal(), (int) iPage.getPages(), brandDTOS);
    }

    @Override
    @Transactional//事物
    public void saveBrandAndCategory(TbBrand brand, List<Long> cids) {
        //保存品牌表
        boolean brandB = this.save(brand);
        if (!brandB) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        Long brandId = brand.getId();
        if (!CollectionUtils.isEmpty(cids)) {
            List list = new ArrayList<TbCategoryBrand>();
            for (Long cid : cids) {
                TbCategoryBrand tbCategoryBrand = new TbCategoryBrand();
                tbCategoryBrand.setBrandId(brandId);
                tbCategoryBrand.setCategoryId(cid);
                list.add(tbCategoryBrand);
            }
            //批量保存 分类品牌 中间表
            categoryBrandService.saveBatch(list);
        }
    }

    @Override
    public void updateBrandAndCategory(TbBrand brand, List<Long> cids) {
      //  System.out.println(brand.getUpdateTime());

        boolean b = this.updateById(brand);
        if (!b) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        Long id = brand.getId();
        if (!CollectionUtils.isEmpty(cids)) {
            QueryWrapper<TbCategoryBrand> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TbCategoryBrand::getBrandId, id);
            boolean remove = categoryBrandService.remove(queryWrapper);
            if (!remove) {
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
            List list = new ArrayList();
            cids.forEach((cid)->list.add(new TbCategoryBrand(cid,id)));
            categoryBrandService.saveBatch(list);
        }
    }

    @Override
    public List<BrandDTO> findBrandByCategoryId(Long categoryId) {
        List<TbBrand> tbBrands = this.baseMapper.selectBrandJoinCategory(categoryId);
        if(CollectionUtils.isEmpty(tbBrands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(tbBrands,BrandDTO.class);
    }

}
